// pages/AddOrEditAddress/AddOrEditAddress.js
const util = require("../../utils/util.js");
var requestManager = require('../../utils/request.js');
var router = require('../../utils/router.js');
const pageName = "EditAddress "
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIpx: app.globalData.isIpx ? true : false,
    isDefault:true, // 是否设置为默认地址
    recommendAreaList: [], // 推荐地址数组
    getDetailedAddressFinished: true, // 即时获取推荐详细地址同步开关
    isShowRecommendPop: false, // 推荐地址组件的显隐
    remarkCount: 0, // 备注字数
    remarkMaxCount: 32, // 备注最大许可数
    areaValue: ['0', '0', '0'], // 所在地区(省市区)数据索引
    provinceList: [{}], // 省列表
    cityList: [{}], // 当前省对应的市列表
    areaList: [{}], // 当前市对应的区列表

    timeValue: ['0', '0', '0'],
    pickerType: 0,

    provinceModel: null,
    cityModel: {},
    areaModel: {},

    timePickerViewisShow: false, // 时间选择器显隐控制
    areaPickerViewisShow: false, // 地址选择器显隐控制

    dayArray: [], // 日期数组(本地生成)
    startArray: ['10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30', '19:00', '19:30', '20:00', '20:30', '21:00', '21:30'],
    endArray: [],
    requestData: {

    },
    postProductArray: [],

    // 用到的卡信息
    orderCardInfo: {
      cardId: "", // 卡id
      productName: "", // 商品名(单品/套餐/虚拟卡名)
      productPath: "", // 单品时对应的商品路径
      productId: "", // 单品时对应的商品ID
      productSetType: 0, // 商品集合类型说明(1蛋糕 2电影 3电子码)
      productList: [], // 商品列表
      productInfoList: [], // 商品信息列表
      addressId:""
    },

    // 用户相关信息
    orderUserInfo: {
      userId: 0, // 用户id
      diyText: "", // 生日牌
      diyTime: "", // 配送时间
      contacts: "", // 收货人
      phone: "", // 联系通电话
      areaText: "", // 所在地区
      provinceId: '', // 省
      cityId: '', // 市
      countyId: '', // 区
      address: "", // 详细地址
      textComment: '', // 备注
    },
    addressInfo:{
      userId: 0, // 用户id
      contacts: "", // 收货人
      phone: "", // 联系通电话
      addressText: "", // 所在地区
      provinceId: '', // 省
      cityId: '', // 市
      countyId: '', // 区
      address: "", // 详细地址
      addressId: "",

    },

    addressGetFocus: false, // 详细地址焦点控制

    turnBackNormal: true, // 非iphone跳转订单确认的销毁
    changeDataWhenInputBlur: true, // 用于记录在详细地址输入框失去焦点时是否采用输入框的数据,当数据是有js设置进去的时,控件显示的是新数据,但底层的数据还是旧的
    requestURL: requestManager.address_add
  },

  /**
    * 生命周期函数--监听页面加载
    */
  onLoad: function (options) {
    console.log("++++++++++",options)
    if (options.contacts == undefined){
      this.data.requestURL = requestManager.address_add
    } else {
      this.data.addressInfo = options
      this.data.requestURL = requestManager.address_update
    }

    this.data.addressInfo.userId = util.getUserInfo().userId;
      // 从上一页获取卡相关信息
      app.globalData.cardDiyText = '';
      this.setData({
        addressInfo: this.data.addressInfo,
      })
      this.initAreaData();
  },

  /**
   * 从上一页获取商品列表
   * 卡信息(cardId,cardName)+卡对应商品列表信息
   */
  _updateData: function () {
    let array = getCurrentPages();
    let page = array[array.length - 2];
    page.data.addressList[page.data.editIndex] = this.data.addressInfo
    page.setData({
      addressList: page.data.addressList
    })
  },
  setIsDefault(){ // 设置地址是否为默认地址
    this.setData({
      isDefault:!this.data.isDefault
    })
  },
  /**
   * 输入框变更
   */
  onValueChanged: function (e) {
    let tag = e.detail.tag;
    let value = e.detail.value;
    if (tag == 'receiverName') {
      // 收货人
      this.data.addressInfo.contacts = value;
    } else if (tag == 'receiverPhoneNum') {
      // 联系电话
      this.data.addressInfo.phone = value;
    } else if (tag == 'detailedAddress') {
      if (e.detail.actionType == 'blur') {
        // 失去焦点
        if (this.data.changeDataWhenInputBlur) {
          this.data.addressInfo.address = value;
        }
      } else if (value.length == 0) {
        this.data.addressInfo.address = value;
        this.data.changeDataWhenInputBlur = true;
        this.setData({
          recommendAreaList: [],
          isShowRecommendPop: false
        })
      } else {
        this.data.addressInfo.address = value;
        this.data.changeDataWhenInputBlur = true;
        if (value.length > 1) {
          this.data.isShowRecommendPop = true;
          if (this.data.getDetailedAddressFinished == true) {
            this._getRecommendAreaList(value);
          }
        }
      }
    }
  },

  /**
   * 点击屏幕隐藏推荐详细地址弹窗
   */
  onWindowClicked: function () {
    if (this.data.isShowRecommendPop) {
      this.setData({
        isShowRecommendPop: false
      })
    }
  },


  /**
   * 实时遍历scope/guess-address
   * 用户填写详细地址时，获取提示输入的下拉列表。
   * 建议1、用户未选择省市区时 提示用户先选择省市区，否则不获取输入提示信息。
   * 建议2、用户输入文本 不小于2个字时再进行提示
   */
  _getRecommendAreaList: function (keyword) {
    let params = {
      userType: 1,
      userId: this.data.addressInfo.userId,
      countyId: this.data.areaModel.value,
      countyAddress: this.data.cityModel.label + this.data.areaModel.label,
      keyword: keyword
    };
    this.data.getDetailedAddressFinished = false;
    requestManager.getDataResult(requestManager.scope_guess_address, params, "GET")
      .then(data => {
        this.data.getDetailedAddressFinished = true;
        if (data.list != undefined && data.list != null && data.list.length > 0) {
          if (this.data.addressInfo.address.length > 0 && this.data.isShowRecommendPop) {
            this.setData({
              recommendAreaList: data.list,
              isShowRecommendPop: this.data.isShowRecommendPop
            })
          }
        }

      }, reject => {
        this.data.getDetailedAddressFinished = true;
      }).catch(e => {

      });
  },

  /**
   * 获取可选城市
   */
  initAreaData: function () {
    let params = {};
    if (this.data.orderCardInfo.productSetType == 1) {
      params.dataScene = "lecakeOrder";
    }
    params.productList = this.data.orderCardInfo.productList;
    params.cardId = this.data.orderCardInfo.cardId;
    params.userId = this.data.addressInfo.userId;

    util.showLoading();
    requestManager.getDataResult(requestManager.scope_area_list, params, "GET")
      .then(data => {
        wx.hideLoading();

        this.data.provinceList = data.optionList;

        let cityDict = data.optionList[0];
        this.data.cityList = cityDict.children;

        let areaDict = this.data.cityList[0];
        this.data.areaList = areaDict.children;

        this.setData({
          provinceList: data.optionList,
          cityList: cityDict.children,
          areaList: areaDict.children,
        })

      }, e => {
        wx.hideLoading();
      }).catch(e => {
        wx.hideLoading();
      });
  },

  /**
   * 选择城市
   */
  selectAreaAction: function (e) {

    // 检测地址数据是否为空
    if (this._checkAddressIsEmpty()) {
      util.noIconToast("套餐内商品配送范围不一致，请更换其它商品");
    } else {
      if (this.data.provinceList.length < 1) {
        return;
      }
      this.data.pickerType = 2;

      //设置弹出
      let array = this.data.provinceList;
      let second = array[this.data.areaValue[0]].children;
      let third = second[this.data.areaValue[1]].children
      let value = this.data.areaValue;

      if (this.data.provinceModel == null || this.data.provinceModel == "") {
        this.data.provinceModel = array[this.data.areaValue[0]];
        this.data.cityModel = second[this.data.areaValue[1]];
        this.data.areaModel = third[this.data.areaValue[2]];
      }

      this.setData({
        areaPickerViewisShow: true,
        ["addressInfo.areaText"]: "请选择"
      });
    }
  },

  //滑动picker 数据变更 
  bindChange: function (e) {
    let val = e.detail.value
    var self = this;
    if (this.data.pickerType == 1) {
      //时间选择
      if (this.data.timeValue[1] != val[1]) {
        this.data.endArray = this.data.startArray.slice(val[1] + 1);

        this.data.endArray.push('22:00');
        this.setData({
          timePickerViewisShow: true,
          endArray: this.data.endArray,
          timeValue: [val[0], val[1], '0'],
        });
        val = [val[0], val[1], '0'];
      }

      this.data.timeValue = val;
      let day = self.data.dayArray[val[0]];
      let start = self.data.startArray[val[1]];
      let end = self.data.endArray[val[2]];
      let timeStr = day + ' ' + start + '-' + end;
      this.data.orderUserInfo.diyTime = timeStr;

    } else {
      this.data.areaValue = val;
      //获取指定对象
      let indexProvince = self.data.provinceList[val[0]];
      let indexcity = self.data.cityList[val[1]];
      let indexarea = self.data.areaList[val[2]];
      //比对本地对象
      if (self.data.provinceModel.value == indexProvince.value) {
        //省份一致

        if (self.data.cityModel.value == indexcity.value) {
          //城市一致

          if (self.data.areaModel.value == indexarea.value) {
            //区域一致
          } else {
            //区域一致
            self.data.areaModel = indexarea;
          }
        } else {
          //城市不一致
          self.data.cityModel = indexcity;
          self.data.areaModel = indexcity.children[0];
          this.data.areaValue = [val[0], val[1], '0'];

          self.setData({
            areaList: indexcity.children,
            areaValue: this.data.areaValue
          });

        }
      } else {
        //省份更新

        self.data.provinceModel = indexProvince;
        indexcity = indexProvince.children[0];
        indexarea = indexcity.children[0];
        self.data.cityModel = indexcity;
        self.data.areaModel = indexarea;
        this.data.areaValue = [val[0], '0', '0'];

        self.setData({
          cityList: indexProvince.children,
          areaList: indexcity.children,
          areaValue: this.data.areaValue
        })
      }
    }
  },

  /**
   * 
   * 点击确定 更新显示数据
   * 
   */
  hidepickerViewIsShow: function () {


    if (this.data.pickerType == 1) {
      //时间
      let isShow;
      if (this.data.timePickerViewisShow) {
        isShow = false;
        this.setData({
          timePickerViewisShow: isShow,
          addressInfo: this.data.addressInfo
        })
      } else {
        isShow = true;
        this.setData({
          timePickerViewisShow: isShow,
          addressGetFocus: false,
          addressInfo: this.data.addressInfo
        })
      }
      return;
    } else {
      //城市
      //设置显示文案
      let text = this.data.provinceModel.label + "-" + this.data.cityModel.label + "-" + this.data.areaModel.label;
      let isShow = true;

      if (this.data.areaPickerViewisShow) {
        isShow = false;
        this.setData({
          ["addressInfo.provinceId"]: this.data.provinceModel.value,
          ["addressInfo.cityId"]: this.data.cityModel.value,
          ["addressInfo.countyId"]: this.data.areaModel.value,
          ["addressInfo.addressText"]: text,
          areaPickerViewisShow: isShow
        })
      } else {
        isShow = true;
        this.setData({
          ["addressInfo.provinceId"]: this.data.provinceModel.value,
          ["addressInfoo.cityId"]: this.data.cityModel.value,
          ["addressInfo.countyId"]: this.data.areaModel.value,
          ["addressInfo.addressText"]: text,
          addressGetFocus: false,
          areaPickerViewisShow: isShow
        })
      }
    }
  },
  /**
   * 选择配送时间
   */
  selectTimeAction: function (e) {
    this.data.pickerType = 1;
    let value = this.data.timeValue;
    this.data.endArray = this.data.startArray.slice(this.data.timeValue[1] + 1);
    this.data.endArray.push('22:00');

    if (this.data.orderUserInfo.diyTime == null || this.data.orderUserInfo.diyTime == "请选择" || this.data.orderUserInfo.diyTime == "") {
      let day = this.data.dayArray[value[0]];
      let start = this.data.startArray[value[1]];
      let end = this.data.endArray[value[2]];
      this.data.orderUserInfo.diyTime = day + ' ' + start + '-' + end;
    }

    this.setData({
      timePickerViewisShow: true,
      endArray: this.data.endArray,
      timeValue: value,
    });
  },

  /**
   * 提交地址
   */
  creationActivityAction: function () {
    var self = this;
    if (self.data.addressInfo.contacts == "") {
      util.noIconToast("请填写收货人", 1000)
      return;
    } else if (self.data.addressInfo.phone == "" || !util.isPhoneNum(self.data.addressInfo.phone)) {
      util.noIconToast("请正确填写手机号", 1000)
      return;
    } else if (self.data.addressInfo.countyId == "") {
      util.noIconToast("请选择区域地址", 1000)
      return;
    } else if (self.data.addressInfo.address == "") {
      util.noIconToast("请填写详细地址", 1000)
      return;
    }

    let params = {};
    params.userId = this.data.addressInfo.userId;
    params.contacts = this.data.addressInfo.contacts;
    params.phone = this.data.addressInfo.phone;
    params.provinceId = this.data.addressInfo.provinceId;
    params.cityId = this.data.addressInfo.cityId;
    params.countyId = this.data.addressInfo.countyId;
    params.address = this.data.addressInfo.address;
    params.addressText = this.data.addressInfo.addressText;
    params.isDefault = this.data.isDefault;
    params.addressId = this.data.addressInfo.addressId;


    util.showLoading();
    requestManager.getDataResult(this.data.requestURL, params, "POST")
      .then(data => {
        wx.hideLoading();
        // util.reportAnalytics("address_post_success");
        // 缓存请求数据
        app.globalData.addressInfo = this.data.addressInfo
        this._updateData()
        wx.navigateBack({
          delta: 1,
        })
      }, e => {
        wx.hideLoading();
        // let msg = e.msgContent;
        // util.reportAnalytics("address_post_fail", {
        //   error_msg: (msg != undefined && msg != null && msg != '') ? msg : "验证失败"
        // })
        // util.noIconToast(msg ? msg : "验证失败", 1000)
      }).catch(e => {
        wx.hideLoading();
        // util.reportAnalytics("address_post_fail", {
        //   error_msg: "本地错误: " + e,
        // })
      });

  },

  /**
   * 页面销毁
   */
  onUnload: function () {
    if (this.data.turnBackNormal) {
      app.globalData.editAddressOrderInfo = undefined;
    }
  },

  /*
   * 推荐详细地址条目点击
   */
  selectedItemAction: function (e) {
    // 数据由外部设置防止输入框在失去焦点时将数据还原
    this.data.changeDataWhenInputBlur = false;

    let content = e.currentTarget.dataset.content;
    this.setData({
      ["orderUserInfo.address"]: content,
      isShowRecommendPop: false,
      recommendAreaList: [],
    })
  },

  /**
   * 检测省市区数组是否为空
   */
  _checkAddressIsEmpty() {

    if (this.data.provinceList != undefined &&
      this.data.provinceList != null &&
      this.data.provinceList.length > 0 &&
      this.data.provinceList[0].label == "" &&
      this.data.provinceList[0].value == "" &&
      this.data.cityList != undefined &&
      this.data.cityList != null &&
      this.data.cityList.length > 0 &&
      this.data.cityList[0].label == "" &&
      this.data.cityList[0].value == "" &&
      this.data.areaList != undefined &&
      this.data.areaList != null &&
      this.data.areaList.length > 0 &&
      this.data.areaList[0].label == "" &&
      this.data.areaList[0].value == "") {
      return true;
    } else {
      return false;
    }
  },

  /**
   * 用于计算当前时间是否在下午八点前
   */
  _isBeforeSixPMTime() {
    let nowDate = new Date();
    let subTime = new Date(nowDate.getFullYear() + "/" + (nowDate.getMonth() + 1) + "/" + nowDate.getDate() + " " + 23 + ":" + 59 + ":" + 59).getTime();
    // 四小时4 * 60 * 60 * 1000 表示再过四小时就第二天了 用于定位晚上八点
    let fourHour = 14399000;
    return ((subTime - fourHour) > nowDate.getTime());
  }

})